package com.base.system.managedBean.baseBean;

import java.io.Serializable;
import java.util.Date;

import javax.faces.model.SelectItem;

import org.operamasks.faces.annotation.Accessible;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.SelectItems;
import org.operamasks.faces.annotation.Validate;
import org.operamasks.faces.component.form.impl.UITextField;

import com.base.common.provider.SelectItemsProvider;
import com.base.commons.SpringBeanHolder;
import com.base.security.entity.SecurityUser;
import com.base.security.service.SecurityEntityManager;

public abstract class BaseSecurityUserBean implements Serializable {
	protected SecurityEntityManager securityEntityManager = SpringBeanHolder
			.getBean("securityEntityManager");
	@Bind(id = "userId", attribute = "binding")
	protected UITextField userId;
	@Bind(id = "username", attribute = "value")
	protected String username;
	@Bind(id = "password", attribute = "value")
	protected String password;
	@Accessible
	private SelectItem[] enabled_items = SelectItemsProvider.getYesNo();
	@SelectItems(source = "#{this.enabled_items}")
	@Bind(id = "enabled", attribute = "value")
	protected boolean enabled = true;
	@Bind(id = "fullname", attribute = "value")
	protected String fullname;
	@Bind(id = "createTime", attribute = "value", value = "#{new Date()}")
	protected Date createTime;
	protected SecurityUser securityUser;

	protected abstract void initSpecialProperty();

	protected void setSecurityUserProperty() {
		if (securityUser == null)
			return;
		securityUser.setCreateTime(createTime);
		securityUser.setEnabled(enabled);
		securityUser.setFullname(fullname);
		securityUser.setPassword(password);
		securityUser.setUsername(username);
		// kr.getSecurityService().createUser(username, password);
	}

	protected void getSecurityUserProperty() {
		if (securityUser == null)
			return;
		userId.setValue(securityUser.getUserId().toString());
		username = securityUser.getUsername();
		fullname = securityUser.getFullname();
		password = securityUser.getPassword();
		createTime = securityUser.getCreateTime();
		enabled = securityUser.isEnabled();
	}

	@Validate(id = { "username" }, message = "用户名已经存在，请选择其他用户名!")
	public boolean validateUsername(String name) {
		// System.out.println("得到的userName is:" + name);
		// 如果userId不为空，则说明是编辑，判断用户名是否变，如果不变，则检验通过。如果变化了，再执行查重判断
		if (userId != null && !"".equals(userId.getSubmittedValue())) {
			// System.out.println("得到的userId is:" + userId);
			// System.out.println("得到的userId value is:"+
			// userId.getSubmittedValue());
			SecurityUser userById = securityEntityManager.getUserById(userId
					.getSubmittedValue().toString());
			if (userById != null && userById.getUsername().equals(name))
				return true;
		}
		SecurityUser su = securityEntityManager.getUserByUsername(name);
		if (su == null)
			return true;
		else
			return false;
	}
}
